import Vue from 'vue';
import VueRouter from 'vue-router';
import { message } from 'ant-design-vue';
import { defaultRoutes } from '@projectCommon/router/routers';
import store from '../store/index';
import { routerInterceptor, project0NoInterceptor } from './interceptor';
import { setFrameLayout } from '@utils';

Vue.use(VueRouter);
// 解决报错 开始
//问题显现控制台：Uncaught (in promise) Error: Navigation cancelled from “/” to “/login” with a new navigation.
//问题原因：这个错误是vue-router内部错误,没有进行catch处理,导致的编程式导航跳转问题,往同一地址跳转时会报错的情况
const originalPush = VueRouter.prototype.push;
const originalReplace = VueRouter.prototype.replace;
// push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject)
    return originalPush.call(this, location, onResolve, onReject);
  return originalPush.call(this, location).catch((err) => err);
};
// replace
VueRouter.prototype.replace = function push(location, onResolve, onReject) {
  if (onResolve || onReject)
    return originalReplace.call(this, location, onResolve, onReject);
  return originalReplace.call(this, location).catch((err) => err);
};

//解决报错 结束

console.log('defaultRoutes', defaultRoutes);
const router = new VueRouter({
  routes: defaultRoutes,
});

// const VueRouterPush = VueRouter.prototype.push;
// VueRouter.prototype.push = function push(to) {
//   return VueRouterPush.call(this.addRoute, to).catch((err) => err);
// };

async function dispatchUserRouter(to, from, next) {
  // store.dispatch('User/getUserInfo').then(() => {
  //   //首先调用获取用户信息接口，如果status返回403，说明未登录，跳转到登录页，如果已经登陆了继续获取用户路由
  //   store
  //     .dispatch('Account/getUserRouter') //User为store模块名称，获取用户路由,
  //     .then(({ code }) => {
  //       if (code == 0) {
  //         next({ ...to, replace: true });
  //       }
  //     })
  //     .catch(({ msg }) => {
  //       message.error(msg || '获取用户路由失败');
  //     });
  // });
  try {
    // Promise.all([
    //   store.dispatch('User/getTenantInfo'),
    //   store.dispatch('Account/getUserRouter'),
    //   store.dispatch('User/getUserInfo'),
    // ])
    //   .then(() => {
    //     next({ ...to, replace: true });
    //   })
    //   .catch(() => {
    //     next({ ...to, replace: true });
    //   });
    await store.dispatch('User/getTenantInfo'); //获取租户信息
    await store.dispatch('User/getUserInfo'); //获取用户信息
    await store.dispatch('Theme/getTheme'); //配置当前皮肤
    await store.dispatch('Account/getUserRouter'); //获取用户路由菜单
    next({ ...to, replace: true });
  } catch ({ msg }) {
    console.log(msg);
  }
}

//全局前置守卫
router.beforeEach((to, from, next) => {
  console.log('所有路由', router.getRoutes());
  const meta = to.meta || {};
  const { requireAuth = true, layout = 'BOTH' } = meta;

  const sessionHasLogin = JSON.parse(sessionStorage.getItem('hasLogin'));
  const {
    User: { hasLogin, project },
  } = store.state;

  const interceptorRouter = Object.keys(routerInterceptor);
  if (!requireAuth) {
    //页面不需要登录权限。直接放行
    next();
  } else if (requireAuth && !sessionHasLogin) {
    //未登录
    dispatchUserRouter(to, from, next);
  } else if (sessionHasLogin && !hasLogin) {
    //sessionHasLogin中存在已登录状态，vuex中没有等已登录状态 说明是刷新页面
    dispatchUserRouter(to, from, next);
  } else if (interceptorRouter.indexOf(to.path) > -1) {
    routerInterceptor[to.path](to, from, next, store);
    //在用户0项目时，拦截非允许访问页面到首页
  } else if (
    project == 0 &&
    !project0NoInterceptor.includes(to.path) &&
    window == window.top
  ) {
    next('/');
    return;
  } else {
    next();
  }
  if (interceptorRouter.indexOf(to.path) == -1) {
    store.commit('Layout/SET_LAYOUT', layout);
  }
  setFrameLayout(store); //当为内嵌iframe 时，设置，头部和左侧的预留宽高
});

export default router;
